<?php

namespace app\admin\controller;

use app\admin\service\LoginService;
use app\common\util\ErrorCode;
use think\App;
use think\facade\Request;

class CommonController
{
    public $params;
    public $noCheckTokenAction = []; //不校验token的方法名，方法名 必须 变成 小写的
    public $returnData = [];
    public $isSuper = false;
    protected $app;
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    public function __construct(App $app)
    {
        if(request()->method() == "OPTIONS"){
            $this->returnData = ErrorCode::$errorCode["request_error"];
            return false;
        }
        $this->params = Request::param('', null);
        unset($this->params["mallData"]);
        $this->app = $app; // 应用对象
        $this->initialize();

        if(!is_array($this->noCheckTokenAction)){
            $this->returnData = ErrorCode::code('params_error', "noCheckTokenAction");
            return false;
        }
        //处理登录token等信息
        if(!in_array(\request()->action(true), $this->noCheckTokenAction)){
            if(isset($this->params['token'])) { //就校验token是否有效或者过期
                if(!$this->getSessionIdVar($this->params["token"])){
                    return false;
                }
            }else{
                $this->returnData = ErrorCode::code('token_expire');
                $this->returnData["msg"] = "token参数不存在";
                return false;
            }
        }
        $this->registerMiddleware();
        return true;
    }

    public function initialize()
    {
        $this->returnData = ErrorCode::code("success");
    }

    public function return_result($data, $text ='')
    {
        if($text && is_string($data['msg']) && strpos($data['msg'], "%s") !== false){
            $data['msg'] = sprintf($data['msg'], $text);
        }
        db()->getConnection()->close(); // 关闭数据库连接
        return json($data);
    }

    /* 获取在缓存中或数据库中用户登录的数据 */
    public function getSessionIdVar($sessionId, $key = '')
    {
        $manageData = LoginService::checkSession($sessionId);
        if (isset($manageData["code"])) {
            $this->returnData = $manageData;
            return false;
        }
        if (is_bool($manageData) && !$manageData) {
            $this->returnData = ErrorCode::code("token_expire");
            return false;
        }
        request()->manageData = $manageData; // 把管理员信息存到request对象里，全局可以调用
        $this->isSuper = $manageData["type"] == '1' ? true : false; // 1 - 超级管理员 | 其它 - 普通管理员
        if (empty($key)) {
            return $manageData;
        }
        if (array_key_exists($key, $manageData)) {
            return $manageData[$key];
        } else {
            return '';
        }
    }

    // 注册控制器中间件
    public function registerMiddleware()
    {
        foreach ($this->middleware as $key => $val) {
            if (!is_int($key)) {
                $only = $except = null;

                if (isset($val['only'])) {
                    $only = array_map(function ($item) {
                        return strtolower($item);
                    }, $val['only']);
                } elseif (isset($val['except'])) {
                    $except = array_map(function ($item) {
                        return strtolower($item);
                    }, $val['except']);
                }

                if (isset($only) && !in_array(request()->action(), $only)) {
                    continue;
                } elseif (isset($except) && in_array(request()->action(), $except)) {
                    continue;
                } else {
                    $val = $key;
                }
            }

            $this->app['middleware']->controller($val);
        }
    }

    //空操作
    public function _empty()
    {
        return $this->return_result(ErrorCode::$errorCode['method_not_exist']);
    }
}
